<?php

class Wechat
{

    protected $appid;
    protected $secret;

    public function __construct()
    {
        $this->appid  = config('wechat.applet.appid');
        $this->secret = config('wechat.applet.appsecret');
    }

    //获取微信接口授权access_token
    public function getWechatAccessToken()
    {
        $re = file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appid&secret=$this->secret");
        $re = json_decode($re, true);
        if ($re && isset($re['access_token'])) {
            $re['expires_in'] = time() + 7000;
            cache('access_token', $re);
        } else {
            throwErr('获取微信access_token出错:' . $re['errmsg']);
        }
    }

    //通过用户登录前端获取的code 获取用户 openid unionid
    public function getWechatOpenid($code)
    {
        $re = file_get_contents("https://api.weixin.qq.com/sns/jscode2session?appid=$this->appid&secret=$this->secret&js_code=$code&grant_type=authorization_code");
        $re = json_decode($re, true);
        if (isset($re['errcode']) && $re['errcode'] != 0) {
            throwErr($re['errmsg']);
        }
        return $re;
    }

    //解密微信信息为了获取用户手机号
    public function decrypt($encryptedData, $iv, $sessionKey)
    {
        if (strlen($sessionKey) != 24) {
            throwErr('encodingAesKey 非法');
        }
        $aesKey = base64_decode($sessionKey);

        if (strlen($iv) != 24) {
            throwErr('初始向量异常');
        }
        $aesIV = base64_decode($iv);

        $aesCipher = base64_decode($encryptedData);

        $result  = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        $dataObj = json_decode($result, true);
        if ($dataObj == NULL) {
            throwErr('aes 解密失败');
        }
        if ($dataObj['watermark']['appid'] != $this->appid) {
            throwErr('aes 解密失败');
        }
        return $dataObj;
    }


    //获取微信绑定手机号
    public function getWechatPhone($code)
    {
        $arr = cache('access_token');
        if (!$arr || $arr['expires_in'] < time()) {
            $this->getWechatAccessToken();
        }

        $access_token = cache('access_token')['access_token'];
        $url          = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$access_token";
        $content      = '{"code":"' . $code . '"}';
        $client       = new \GuzzleHttp\Client();
        try {
            $response = $client->post($url, ['body' => $content]);
            $re       = json_decode($response->getBody()->getContents(), true);
            if ($re['errcode'] != 0) {
                throwErr($re['errmsg']);
            }
            return $re['phone_info']['purePhoneNumber'];
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            echo $e->getRequest();
            if ($e->hasResponse()) {
                echo $e->getResponse();
            }
            die;
        }
        return;
    }


    //通过openid 获取微信的用户信息
    public function getWechatUserInfo($openid)
    {
        $access_token = cache('access_token')['access_token'];
        $re           = file_get_contents("https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN");
        $re           = json_decode($re, true);
        if ($re && isset($re['errcode'])) {
            throwErr($re['errmsg']);
        }
        return $re;
    }

    //获取用户unionid
    public function getUserUnionId($openid, $transaction_id)
    {
        $access_token = cache('access_token')['access_token'];
        $re           = file_get_contents("https://api.weixin.qq.com/wxa/getpaidunionid?access_token=$access_token&openid=$openid&transaction_id=$transaction_id");
        $re           = json_decode($re, true);
        if ($re && isset($re['errcode'])) {
            F($re['errmsg']);
        }
        return $re;
    }

    /**
     * Notes: 敏感词检测
     * User: 丁一
     * Date: 2021/4/9
     * Time: 11:31
     * @param $content
     */
    public function msgSecCheck($content)
    {
        $access_token = cache('access_token')['access_token'];
        $url          = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=$access_token";
        $content      = '{"content":"' . $content . '"}';
        $client       = new \GuzzleHttp\Client();
        try {
            $response = $client->post($url, ['body' => $content]);
            $re       = json_decode($response->getBody()->getContents(), true);
            if ($re['errcode'] == 87014) {
                F('包含敏感词,请重新输入');
            }
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            echo $e->getRequest();
            if ($e->hasResponse()) {
                echo $e->getResponse();
            }
            die;
        }
        return;
    }

    //无限小程序码
    public function getUnlimitQRCode($path = '', $scene = '')
    {
        $arr = cache('access_token');
        if (!$arr || $arr['expires_in'] < time()) {
            $this->getWechatAccessToken();
        }

        $access_token  = cache('access_token')['access_token'];
        $url           = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$access_token";
        $body['scene'] = $scene;
        if ($path) {
            $body['page'] = $path;
        }
        $body = json_encode($body);

        $client = new \GuzzleHttp\Client();
        try {
            $response = $client->post($url, ['body' => $body]);
            $re       = $response->getBody()->getContents();//json_decode($response->getBody()->getContents(), true);
            $re1 = json_decode($re,true);
            if (isset($re1['errcode']) && $re1['errcode'] != 0) {
                throwErr($re1);
            }
            return $re;
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            throw new \think\Exception($e);
            echo $e->getRequest();
            if ($e->hasResponse()) {
                echo $e->getResponse();
            }
            die;
        }
        return;
    }

    /**
     * Notes: 微信移动应用App登录
     * User: 丁一
     * Date: 2021/5/20
     * Time: 16:20
     */
    public function wechatAppLogin($code)
    {
        $appid  = config('wechat.app.appid');
        $secret = config('wechat.app.secret');
        $re     = file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code");
        $re     = json_decode($re, true);
        if (isset($re['errcode']) && $re['errcode'] != 0) {
            msg('', isset($re['errcode']) ? $re['errcode'] : 404, $re['errmsg']);
        }
        return $re;
    }

    public function wechatAppUserInfo($access_token, $openid)
    {
        $re = file_get_contents("https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid");
        $re = json_decode($re, true);
        if (isset($re['errcode']) && $re['errcode'] != 0) {
            msg('', isset($re['errcode']) ? $re['errcode'] : 404, $re['errmsg']);
        }
        return $re;
    }


}